package com.supermap.dialogs;

import com.supermap.Helper;
import com.supermap.consts.AttrConsts;
import com.supermap.data.*;
import com.supermap.dialogs.advance.CJDialog;
import com.supermap.mapping.*;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class SqlQueryDialog extends CJDialog {
    private Map map;
    private JSplitPane dataPane;

    private JTable sqlResultTable;
    private JTextField selectFieldsTextField;
    private JTextField whereFilterTextField;
    private JTextField orderByFieldsTextField;
    private JTextField groupByFieldsTextField;
    private JPopupMenu popupMenu;

    private String datasetName;
    private Layer currentLayer;

    public SqlQueryDialog(Frame owner, String title, boolean modal, Map map, JSplitPane dataPane) {
        super(owner, title, modal, 400, 200, new Object[]{map, dataPane});
    }

    @Override
    protected void initializeArgs(Object[] args) {
        this.map = (Map) args[0];
        this.dataPane = (JSplitPane) args[1];
    }

    @Override
    protected void initializeCore() {
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        super.confirmBtn.setText("查询");

        JPanel topPanel = new JPanel();
        topPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

        JLabel datasetLabel = new JLabel("数据集: ");
        topPanel.add(datasetLabel);

        JComboBox<String> datasetComboBox = new JComboBox<>();
        Layers layers = map.getLayers();
        for (int i = 0; i < layers.getCount(); i++) {
            Layer layer = layers.get(i);
            Dataset dataset = layer.getDataset();
            datasetComboBox.addItem(dataset.getName());
        }
        datasetComboBox.addItemListener(e -> {
            datasetName = (String) e.getItem();
            DefaultTableModel model = (DefaultTableModel) sqlResultTable.getModel();
            model.setColumnIdentifiers(new Object[0]);
            model.getDataVector().clear();
            model.fireTableDataChanged();
        });
        datasetComboBox.setSelectedIndex(0);
        datasetName = (String) datasetComboBox.getSelectedItem();
        topPanel.add(datasetComboBox);

        add(topPanel, BorderLayout.NORTH);

        JLabel selectFieldsLabel = new JLabel("查询属性: ");
        selectFieldsTextField = new JTextField();
        selectFieldsTextField.setText(AttrConsts.WILDCARD);
        JPanel selectPanel = new JPanel();
        selectPanel.setLayout(new BorderLayout());
        selectPanel.add(selectFieldsLabel, BorderLayout.WEST);
        selectPanel.add(selectFieldsTextField, BorderLayout.CENTER);

        JLabel whereFilterLabel = new JLabel("过滤条件: ");
        whereFilterTextField = new JTextField();
        JPanel wherePanel = new JPanel();
        wherePanel.setLayout(new BorderLayout());
        wherePanel.add(whereFilterLabel, BorderLayout.WEST);
        wherePanel.add(whereFilterTextField, BorderLayout.CENTER);

        JLabel orderByFieldsLabel = new JLabel("排序属性: ");
        orderByFieldsTextField = new JTextField();
        JPanel orderPanel = new JPanel();
        orderPanel.setLayout(new BorderLayout());
        orderPanel.add(orderByFieldsLabel, BorderLayout.WEST);
        orderPanel.add(orderByFieldsTextField, BorderLayout.CENTER);

        JLabel groupByFieldsLabel = new JLabel("分组属性: ");
        groupByFieldsTextField = new JTextField();
        JPanel groupPanel = new JPanel();
        groupPanel.setLayout(new BorderLayout());
        groupPanel.add(groupByFieldsLabel, BorderLayout.WEST);
        groupPanel.add(groupByFieldsTextField, BorderLayout.CENTER);

        JPanel queryPanel = new JPanel();
        queryPanel.setLayout(new GridLayout(4, 0));
        queryPanel.add(selectPanel);
        queryPanel.add(wherePanel);
        queryPanel.add(orderPanel);
        queryPanel.add(groupPanel);

        sqlResultTable = new JTable();
        sqlResultTable.getSelectionModel().addListSelectionListener(e -> {
            Selection selection = currentLayer.getSelection();
            selection.clear();
            int[] selectedIndices = ((DefaultListSelectionModel) e.getSource()).getSelectedIndices();
            for (int i = 0; i < selectedIndices.length; i++) {
                selectedIndices[i] += 1;
            }
            selection.addRange(selectedIndices);
            GeoStyle selectionStyle = selection.getStyle();
            selectionStyle.setFillBackColor(Color.RED);
            selectionStyle.setFillForeColor(Color.RED);
            selectionStyle.setLineColor(Color.RED);
            selection.setStyleOptions(StyleOptions.FILLBACKCOLOR, true);
            selection.setDefaultStyleEnabled(false);
            Recordset recordset = selection.toRecordset();
            Rectangle2D bounds = recordset.getBounds();
            if (bounds.getLeft() == bounds.getRight()) {
                Point2D center = bounds.getCenter();
                bounds = new Rectangle2D(center.x - 0.5, center.y + 0.5, center.x + 0.5, center.y - 0.5);
            }
            map.setViewBounds(bounds);
            map.refresh();
        });
        add(queryPanel, BorderLayout.CENTER);
    }

    @Override
    protected void doConfirmCore() {
        Dataset dataset = null;
        currentLayer = null;
        Layers mapLayers = map.getLayers();
        for (int i = 0; i < mapLayers.getCount(); i++) {
            Layer layer = mapLayers.get(i);
            Dataset tempDataset = layer.getDataset();
            if (tempDataset.getName().equals(datasetName)) {
                dataset = tempDataset;
                currentLayer = layer;
                break;
            }
        }

        if (!(dataset instanceof DatasetVector)) {
            return;
        }

        String[] selectFields = selectFieldsTextField.getText().replace(AttrConsts.SPACE, AttrConsts.EMPTY).split(AttrConsts.COMMA);
        String whereFilter = whereFilterTextField.getText();
        String[] orderByFields = orderByFieldsTextField.getText().replace(AttrConsts.SPACE, AttrConsts.EMPTY).split(AttrConsts.COMMA);
        String[] groupByFields = groupByFieldsTextField.getText().replace(AttrConsts.SPACE, AttrConsts.EMPTY).split(AttrConsts.COMMA);

        DatasetVector datasetVector = (DatasetVector) dataset;
        QueryParameter queryParameter = new QueryParameter();
        queryParameter.setCursorType(CursorType.STATIC);
        queryParameter.setHasGeometry(true);
        queryParameter.setResultFields(selectFields);
        queryParameter.setAttributeFilter(whereFilter);
        queryParameter.setOrderBy(orderByFields);
        queryParameter.setGroupBy(groupByFields);
        Recordset recordset = datasetVector.query(queryParameter);
        Helper.loadTabular(recordset, sqlResultTable);
        JScrollPane sqlResultScrollPane = new JScrollPane(sqlResultTable);
        JTabbedPane dataTabPane = new JTabbedPane();
        dataTabPane.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (popupMenu != null && popupMenu.isVisible()) {
                    popupMenu.setVisible(false);
                }
                switch (e.getButton()) {
                    case MouseEvent.BUTTON1:
                        break;
                    case MouseEvent.BUTTON2:
                        break;
                    case MouseEvent.BUTTON3:
                        popupMenu = new JPopupMenu();
                        JMenuItem closeItem = new JMenuItem("关闭");
                        closeItem.addActionListener(e1 -> {
                            popupMenu.setVisible(false);
                            dataTabPane.remove(sqlResultScrollPane);
                            if (dataTabPane.getTabCount() == 0) {
                                dataPane.setBottomComponent(null);
                            }
                            Selection selection = currentLayer.getSelection();
                            selection.clear();
                        });
                        popupMenu.add(closeItem);
                        popupMenu.setLocation(e.getLocationOnScreen());
                        popupMenu.setVisible(true);
                        break;
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {

            }

            @Override
            public void mouseReleased(MouseEvent e) {

            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseExited(MouseEvent e) {

            }
        });
        dataTabPane.addTab("SQL查询结果", sqlResultScrollPane);
        dataPane.setBottomComponent(dataTabPane);
        dataPane.setDividerLocation((int) (dataPane.getHeight() * 0.7));
    }
}
